﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gollie.DataTables;
using Gollie.Payment.Targetpay;

namespace Gollie.Controls
{
	public partial class IDealPayment : AuthenticationRequiredCustomerBaseUserControl
	{
		protected override void OnPostBack(object sender, EventArgs e)
		{
			decimal totPrice;
			decimal totCredit;
			this.OrderBasketData.Sum(out totCredit, out totPrice);

			this.HandlePayment(totPrice);
		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			this.Populate();
		}

		private void Populate()
		{

			IDealBanks ideal = new IDealBanks(true);

			BankCollection banks = ideal.Banks;

			foreach (Bank bank in banks)
			{
				this.DropDownList1.Items.Add(new ListItem(bank.Name, bank.Id));
			}
		}

		private void HandlePayment(decimal amount)
		{
			if (amount <= 0 || amount > 10000) //upper limit for targetpay
				this.Response.Redirect("/UI/Forms/LogOut.aspx", true);

			decimal amount10 = amount * 100;
			//amount10 += 129; //€ 1,29 kosten

			string bankid = this.DropDownList1.SelectedValue;// this.Request["targetpayBankSelect"];

			IDealFetch idealFetch = new IDealFetch
				(
					false //TESTMODE
					, this.UserInfo.Gebruikersnaam + ", Gollie"
					, ConfigAppSettings.GetValue("idealreporthandler")
					, ConfigAppSettings.GetValue("idealreturnhandler")
					, bankid
					, amount10
				);

			if (idealFetch.Error == false)
			{
				try
				{
					Database.Queries.InsertDeposit(idealFetch.TransactionId, this.UserInfo.Id, amount, 1, this.OrderBasketData);

					Session.Remove("orderbasket");

					this.Response.Redirect(idealFetch.Url, true);
				}
				catch (MySql.Data.MySqlClient.MySqlException ex)
				{
					this.Panel1.Visible = false;
					this.ErrorPanel.Visible = true;
					this.lblErrorMsg.Text = MySqlErrorCodes.GetInstance().GetMessage(ex);
				}
			}
			else
			{
				this.Panel1.Visible = false;
				this.ErrorPanel.Visible = true;
				this.lblErrorMsg.Text = "De iDEAL omgeving is op het moment onbereikbaar. Probeert u het later nog eens.";
			}
		}
	}
}